<template>
    <div class="register-form">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">

            <el-form-item class="role-row" prop="role_id">
                <el-checkbox-group class="role-checkbox" v-model="form.role_id" @change="changeRole">
                <el-checkbox :label="6" border name="type">教师</el-checkbox>
                <el-checkbox :label="4" border name="type">学生</el-checkbox>
                <el-checkbox :label="5" border name="type">家长</el-checkbox>
                </el-checkbox-group>
            </el-form-item>    

            <el-form-item label="学校" prop="school_id" v-if="!isSchool">
                <el-select v-model="form.school_id" @change="selectSchool" placeholder="请选择学校" >
                    <el-option v-for="item of schoolData" :label="item.name" :value="item.id" :key="item.id"></el-option>
                </el-select>
            </el-form-item>

            <!-- 班级部分 注意：仅仅是家长的身份，是没有班级的-->
            <template v-if="schoolAppCode && !(form.role_id.length === 1 && form.role_id[0] === 5)">
                <el-form-item>
                    <el-radio-group v-model="form.invite">
                        <el-radio :label="1">有班级邀请码</el-radio>
                        <el-radio :label="0">无班级邀请码</el-radio>
                    </el-radio-group>
                </el-form-item>     

                <!-- 有班级邀请码部分 -->
                <div v-if="form.invite === 1">
                    <template>
                        <el-form-item class="invite-row" v-for="(item,index) of form.inviteCodes" :key="index" :label="index === 0 ? '邀请码' : `邀请码${index + 1}`" :prop="'inviteCodes.' + index + '.code'" 
                        :rules="[{ required: true, message: '请输入邀请码', trigger: 'blur' }]"
                        >
                            <div>
                                <el-input v-model.trim="item.code" placeholder="6位字符，区分大小写" @change="validateCode(item.code,index)" :minlength="6" :maxlength="6"></el-input>
                                <el-button type="primary" icon="el-icon-plus" circle size="mini" v-show="!form.role_id.includes(4) && form.inviteCodes.length < 5" @click="addCode(index)"></el-button>
                                <el-button type="primary" icon="el-icon-minus" circle size="mini" v-if="index !== 0" @click="delCode(index)"></el-button>
                            </div>
                            <div class="class-name" v-if="item.class && item.class.name">
                                <span>{{item.class.name}}</span>
                            </div>
                        </el-form-item>
                    </template>
                    <el-form-item>
                        <div class="invite-tip" v-if="form.role_id.includes(6) && schoolAppCode && form.invite === 1">
                            <img src="./../../../../public/images/xinzhuce_05.png">
                            <span>教师负责多个班级，请点击增加按钮绑定</span>
                        </div>
                    </el-form-item>
                </div>

                <!-- 无班级邀请码部分 -->
                <div v-else>
                    <el-form-item label="班级" prop="class_ids" :key="form.role_id[0]">
                        <el-cascader
                            ref="classCascader"
                            v-model="form.class_ids"
                            :options="classData"
                            :props="classProps"
                            clearable>
                        </el-cascader>
                    </el-form-item>                    
                </div>
            </template>

            <template v-if="form.role_id.includes(5)">
                <el-tabs v-model="tabIndex" type="card" editable @edit="editTab">
                    <el-tab-pane v-for="(item, index) in form.childrens" :key="index" :label="item.title" :name="item.inx">
                        <div class="content">
                            <el-form-item label="子女账号" :prop="'childrens.' + index + '.number'" :rules="[{ required: true, message: '请输入子女账号', trigger: 'blur' }]">
                                <el-input v-model.trim="item.number" placeholder="请输入子女账号" maxlength="20"></el-input>
                            </el-form-item>
                            <el-form-item label="密码" :prop="'childrens.' + index + '.password'" :rules="[{ required: true, message: '请输入子女账号的密码', trigger: 'blur' }]">
                                <el-input type="password" v-model.trim="item.password" placeholder="请输入子女账号的密码" autocomplete="off" maxlength="20" @change="checkChildren($event,item,index)"></el-input>
                            </el-form-item>                            
                            <template>
                            </template>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </template>

            <el-form-item class="user-item-row" label="用户名" prop="name">
                <el-input v-model.trim="form.name" minlength="1" maxlength="20"  placeholder="请填写真实姓名"></el-input>
            </el-form-item>

            <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="form.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="任教科目" v-if="form.role_id.includes(6)">
                <el-select v-model="form.subject_ids" placeholder="请选择科目" @change="selectSubject">
                    <el-option v-for="item of subjectData" :label="item.name" :value="item.id" :key="item.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="账号" prop="number">
                <el-input v-model="form.number" maxlength='16' placeholder="用于登录（建议输入学号/工号）"></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="Tpassword">
                <el-input type="password" v-model.trim="form.Tpassword" autocomplete="off" maxlength='16' placeholder="密码限制8~16，由数字、大写字母、小写字母，特殊符号3种或3种以上组合组成"></el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="repassword">
                <el-input type="password" v-model.trim="form.repassword" autocomplete="off" maxlength='16' placeholder="密码限制8~16，由数字、大写字母、小写字母，特殊符号3种或3种以上组合组成"></el-input>
            </el-form-item>

            <el-form-item class="telphone-item-row" label="手机号码" prop="telphone">
                <el-input v-model="form.telphone" placeholder="输入11位手机号码" maxlength="11"></el-input>
            </el-form-item>

            <el-form-item class="tips-item-row">
                <div class="invite-tip" v-if="form.role_id.includes(6)">
                    <img src="./../../../../public/images/xinzhuce_05.png">
                    <span>非必填，可用于接收审核结果通知；需院校开通短信接口</span>
                </div>
            </el-form-item>

            <el-button class="submit-btn" type="primary" @click="submitForm('form')">提交注册</el-button>
        </el-form>
        		<!-- 弹窗：查看注册的信息 -->
		<el-dialog class="global-dialog register-dialog" title="提示" :visible.sync="dialogVisible" @close="dialogVisible = false">
			<register-info v-if="dialogVisible" ref="registerInfo" :opctions='form' :otherOpctions='otherOpctions'></register-info>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="surePost">确定无误，提交注册</el-button>
            </span>
    	</el-dialog>
    </div>
</template>
<script>
import registerInfo  from "./register-info";
export default {
    components: {
        registerInfo
    },
    data() {
        var validatePass = (rule, value, callback) => {
            const reg = /^[\w]{6,16}$/;
            const lengthFlag = value.length < 6;
            const typeFlag = !reg.test(value);
            if (value === '') {
                callback(new Error('请输入密码'));
            } else if(lengthFlag && lengthFlag){
                callback(new Error('密码由6~16位英文、数字、下划线组成'));
            }else if(lengthFlag){
                callback(new Error('请输入6~16位字符的密码'));
            } else if(typeFlag){
                callback(new Error('密码必须是由英文、数字、下划线组成'));
            }else {
                if (this.form.repassword !== '') {
                    this.$refs.form.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.form.Tpassword) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };        
        return {
            form: {
                role_id: [6],
                invite:1,
                school_id:'',
                name: '',
                number: '',
                Tpassword: '',
                repassword: '',
                class_ids:[],
                subject_ids:'',
                children_ids:'',
                sex:1,
                app_code: '',
                telphone: '',
                inviteCodes:[{
                    code:'',
                    class:{}
                }],
                childrens:[{
                    inx:'1',
                    id:'',
                    title:'子女1',
                    name:'',
                    password:''
                }]
            },
            otherOpctions:{
                schoolName:'',
                teachClass:'',
            },
            tabIndex: '1',
            rules: {
                role_id: [
                    { required: true, message: '请选择角色', trigger: 'change' }
                ],                
                school_id: [
                    { required: true, message: '请选择学校', trigger: 'change' }
                ],
                class_ids: [
                    { required: true, message: '请选择班级', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 1, max: 20, message: '用户名的长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '请选择性别', trigger: 'change' }
                ],
                number: [
                    {pattern: this.rules.account.reg, message: this.rules.account.msg, trigger: 'blur'},
                    { required: true, message: '请输入登录账号', trigger: 'blur'}
                ],
                Tpassword: [
                   { required: true, validator: validatePass, trigger: 'blur' }
                ],
                repassword: [
                   { required: true, validator: validatePass2, trigger: 'blur' }
                ],
                telphone: [
                    {pattern: this.rules.mobile.reg, message: this.rules.mobile.msg, trigger: 'blur'},
                    {message: '请输入手机号码', trigger: 'blur'}
                ],
            },
            schoolData:[],
            schoolAppCode:'',
            classData:[],
            subjectData:[],
            dialogVisible:false
        };
    },
    created(){
        this.getSchool();
    },
    mounted(){
        if(this.isSchool){
            let code = sessionStorage.getItem('CheckSchoolAppCode');
            this.form.app_code = code;
            this.schoolAppCode = code;
            this.getClass(code);  
            this.getSubject(code);  
        }
    },
    computed: {
        isSchool(){
            return this.$store.getters.isSchool;
        },
        // 班级-级联选择器设置
        classProps(){
            return {
                children: 'children',
                label: "name",
                value: "id",
                multiple: !this.form.role_id.includes(4)//教师角色的班级可多选，学生角色单选
            }
        },
    },
    methods:{

        // 选择角色
        changeRole(val){
            const newVal = val[val.length - 1];//最新勾选的这个角色id
            // 角色互斥处理 ：教师和家长可以同时选择，并和学生角色互斥
            this.form.role_id = val.filter(x => {
                 return newVal === 4 ? (x != 6 && x != 5) : (x != 4);
            })
            // 邀请码（班级）：学生角色只能有一个；教师可绑定多个
            if(newVal === 4 && this.form.inviteCodes.length > 1){
                this.form.inviteCodes = this.form.inviteCodes.filter((x,inx)=>{return inx === 0});
                console.log(this.form.inviteCodes)
            }
            if(!this.form.role_id.includes(6)){
                this.form.subject_ids = ''
            }
            // 学生角色和教师身份切换的时候，重置班级选择框
            this.form.class_ids = [];
        },
        validateCode(code,index){
            const len = this.form.inviteCodes.length;
            for (let i = 0; i < len; i++) {
                const x = this.form.inviteCodes[i];
                if(x.code === code && i != index){
                    this.clearCodeInput(index);
                    this.$message.error('此验证码对应的班级已经绑定了，不需要重复绑定同一班级');
                    return;
                }
            }
            let success = res => {
                const data = res.data;
                console.log(res.data[0])
                if(data.length > 0){
                    this.form.inviteCodes[index].class = res.data[0];
                }else{
                    this.clearCodeInput(index);
                    this.$message.error('请输入正确的验证码');
                }
            };
            let fail = res => {
                this.clearCodeInput(index);
                this.$message.error('请输入正确的验证码');
            };
			this.$ajax({
				url: 'api/org/get_class_by_password',
				method: 'get',
				params: {
                    level: 4,
                    direction: 'balance',
                    password: code,
                    app_code:this.schoolAppCode                    
                },
				func: { 
                    success: success,
                    fail: fail
                }
			});
        },
        clearCodeInput(index){
            this.form.inviteCodes[index].code = '';
            this.form.inviteCodes[index].class = {};
        },
        addCode(index){
            this.form.inviteCodes.push({
                code:'',
                class:{}
            });
        },
        delCode(index){
            this.form.inviteCodes = this.form.inviteCodes.filter((x,y) => { return y != index});
        },
        // 获取所有学校的数据
        getSchool(){
            let success = (res=>{
                this.schoolData = res.data;
            });
            this.$ajax({
                url: 'api/level/get_school_by_postionid',
                method: 'get',
                params: {
                    server_type: 1
                },
                func: {success: success}
            })
        },
        selectSchool(id){
            console.log(id,this.schoolData)
            let code = '';
            this.schoolData.map(x => {
                if(x.id === id){
                    code = x.app_code;
                    this.otherOpctions.schoolName = x.name;
                }
            })
            this.form.app_code = code;
            this.schoolAppCode = code;
            
            // 重置数据
            this.form.class_ids = [];
            this.getClass(code);

            this.form.subject_ids = '';
            this.getSubject(code); 
            
            this.form.inviteCodes = [{
                code:'',
                class:{}
            }];
            this.tabIndex = '1';
            this.form.childrens = [{
                inx:'1',
                id:'',
                title:'子女1',
                name:'',
                password:''
            }]
            this.form.children_ids = '';
        },
        getClass(code){
            let success = res => {
                console.log(res.data)
                this.classData = this.setDisabled(res.data);
            };
            this.$ajax.get('api/newlevel/platform_org', {
                params: {
                    app_code: code,
                    level:2,
                    direction:"down",
                    data_type:"arr_all"
                },
                func: { success: success }
            });                
        },
        // 班级联级选择器设置禁止选中：不符合学段-年级-班级这样的层级的，设置禁用
        setDisabled(data){
            const length = data.length
            for (var i = 0; i < length; i++) {
                const item = data[i];
                if(item.children != ''){
                    this.setDisabled(item.children);
                }else if(item.level < 4 && item.children === ''){
                    item.disabled = true;
                }
			}
			return data;
        },        
        // 教师角色-获取任教科目
        getSubject(code){
            if(this.form.role_id.includes(6)){
                let success = (res =>{
                    this.subjectData = res.data;
                });
                this.$ajax({
                    url: 'api/newlevel/platform_subject',
                    methed: 'get',
                    params:{
                        app_code:code,
                    },
                    func:{success: success}
                })
            }
        },   
        selectSubject(val){
            this.otherOpctions.teachClass = this.subjectData.filter(x => {return val === x.id})[0].name;
        }, 
        // 新增或者删除tab
        editTab(targetName, action) {
            const counts = this.form.childrens.length;
            if (action === 'add') {
                if(counts === 5){
                    this.$message.warning('最多只能绑定5个子女的账号');
                    return;
                }                    
                let newTabName = counts + 1 + '';
                this.tabIndex = newTabName;
                this.form.childrens.push({
                    inx:newTabName,
                    id:'',
                    title:`子女${newTabName}`,
                    number:'',
                    password:''
                });
            } else if (action === 'remove') {
                if (counts <= 1) {
                    this.$message.warning('只剩下一位子女账号了，不能再删除了');
                    return;
                }
                let tabs = deep_clone(this.form.childrens);
                // 删除项并重排每项的索引
                this.form.childrens = tabs.filter(tab => tab.inx !== targetName).map((tab, inx) => {
                    const newInx = ++inx + '';
                    tab.inx = newInx
                    tab.title = tab.title.includes('子女') ? `子女${newInx}` : tab.title;
                    return tab;
                });
                // //重设高亮状态
                const a = this.tabIndex;
                const b = targetName < 5 || (targetName == a && targetName != '1') ? a - 1 : a;
                this.tabIndex = b === 0 ? '1' : b.toString();
            }
            // console.log(this.form.childrens)
        },     
        checkChildren(e,item,inx){
            // console.log(e,item)
            let success = (res=>{
                const data = res.data;
                // console.log(res.data)
                if(data.role_base_id.includes(4)){//账号密码输入正确获取到数据后，要判断一下是否是学生账号，不是学生的账号不绑定
                    this.form.childrens[inx].id = data.id;
                    this.form.childrens[inx].title = data.name;
                    this.form.childrens[inx].name = data.name;
                    this.form.childrens[inx].class_name = data.class_name;
                    // this.$message.success(res.msg);
                    this.$message.success('子女帐号密码正确');
                }else{
                    this.clearInput(inx);
                    this.$message.error('此账号不属于学生身份，无法绑定');
                }
            })

            let fail = (res=>{
                this.clearInput(inx);
                this.$message.error(res.msg);
            })
            this.$ajax({
                url: 'api/user/check_user',
                method: 'get',
                params: {
                    number: item.number,
                    password: item.password
                },
                func: {success: success, fail: fail}
            })
        },
        // 绑定子女账号不成功，清理一下输入内容
        clearInput(inx){
            this.form.childrens[inx].password = '';
            this.form.childrens[inx].id = '';
            this.form.childrens[inx].name = '';
            this.form.childrens[inx].class_name = '';
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.dialogVisible = true;
                } else {
                    console.log('error submit!!');
                    if(this.form.role_id.includes(5)){
                        const errorTips = this.form.childrens.map(x => {
                            if(x.password ==='' || x.number === ''){
                                return x.title;
                            }
                        }).join(' ');
                        console.log(errorTips)
                        if(errorTips){
                            this.$message.error(`${errorTips}的账号和密码有误，请检查一下，再提交注册`)
                        }
                    }
                    return false;
                }
            });
        },
        surePost(){
            this.dialogVisible = false;
            let params = deep_clone(this.form);
            if(params.invite === 1){
                params.class_ids = params.inviteCodes.map(x => {return x.class.id}).toString();
            }else{
                params.class_ids = params.role_id.includes(4) ? params.class_ids[2] : params.class_ids.map(x => {return x[2]}).toString();
            }
            params.children_ids = params.childrens.map(x => {return x.id}).toString();
            params.role_id = params.role_id.toString();
            // 删除多余项
            delete params.inviteCodes;
            delete params.childrens;
            delete params.invite;
            console.log(params)
            let success = (res =>{
                this.$message.success(res.msg);
                this.$router.push('/');
            })
            let fail = (res =>{
                this.$message.error(res.msg);
            })            
            this.$ajax({
                url: 'api/user/user_apply',
                method: 'post',
                data: params,
                func: {success,fail}
            })
        },        
    }
};
</script>
<style lang="scss">
    .el-form-item{
        .el-form-item__label{
            text-align: left;
        }
    }
    .el-select{
        width: 100%;
    }
    .role-row{
        .el-form-item__content{
            margin-left: 0!important;
        }
    }
    .role-checkbox{
        padding-bottom: 40px;
        border-bottom: 1px solid #ddd;
        .el-checkbox {
            height: 80px;
            line-height: 42px;
            margin-right: 12px;
            padding: 18px 48px 18px 38px;
            border: 1px solid #f0f4fd;
            background-color: #f0f4fd;
            position: relative;
            &:last-child{
                margin-right: 0;
            }
            .el-checkbox__inner{
                width: 18px;
                height: 18px;
                border-radius: 50%;
                &::after{
                    left: 6px;
                    top: 3px;
                }
            }
        }
        .el-checkbox.is-checked{
            border: 1px solid #c1d7ff;
            background-color: #c1d7ff;
            &::after{
                content: "";
                display: inline-block;
                width: 20px;
                height: 20px;
                border: 1px solid #ddd;
                transform: rotateZ(45deg);
                position: absolute;
                left: 60px;
                bottom: -52px;
                background-color: #fff;
                border-width: 1px;
                border-style:solid;
                border-color:#ddd#fff #fff #ddd;
            }                    
        }
        .el-checkbox.is-bordered+.el-checkbox.is-bordered {
            margin-left: 0;
        }        
    }
    .invite-row{
        .el-input{
            width: 300px;
            margin-right: 10px;
        }
        .el-button{
            padding: 2px;
        }
        .class-name span{
            padding: 5px 10px;
            font-size: 12px;
            color: #ab4f15;
            background: #fffadc;
        }
    }
    .user-item-row,.telphone-item-row{
        padding-top: 30px;
        border-top: 1px dashed #e8e8e8;
    }
    .tips-item-row{
        border-bottom: 1px dashed #e8e8e8;
    }
    .invite-tip{
        img,span{
            vertical-align: middle;
        }
        span{
            margin-left: 5px;
            font-size: 12px;
            color: #333;
        }
        .el-divider{
            margin: 12px 0;
        }
    }
    .submit-btn{
        width: 100%;
    }
</style>